/**
 * 游戏全局断线重连模块
 * @author none
 *
 */
class ReConnectedModule extends how.module.GlobalModule 
{
    public static response: any = 
    {
        gameHide: how.Application.APPEVENT_PAUSE,
        gameShow: how.Application.APPEVENT_RESUME,
        onSocketOpen: egret.Event.CONNECT,//网络连接成功
        onSocketClose: egret.Event.CLOSE,
        onHeartbeat1: CMDConfig.SEND_HEARTBEAT1,//收到心跳包
        onHeartbeat2: CMDConfig.SEND_HEARTBEAT2,//收到心跳包
        setIsThrowOut: "setIsThrowOut",
    }

    public isThrowOut: Boolean = false;
    public sendHeartbeatDate: number = 0;
    public sendHeartbeatTimers: number = null;
    public currentSocket: how.WebSocketManager = null;

    //网络连接成功
    public onSocketOpen(data: any): void 
    {
        if (data.host == this.hallSocket.host && data.port == this.hallSocket.port) 
        {
            this.currentSocket = this.hallSocket;
        }

        if (this.sendHeartbeatTimers) 
        {
            egret.clearTimeout(this.sendHeartbeatTimers);
            this.sendHeartbeatTimers = null;
        }
        this.sendHeartbeatTimers = egret.setTimeout(this.sendHeartbeat, this, 30 * 1000);
    }

    //发送心跳包
    public sendHeartbeat(): void 
    {
        this.sendHeartbeatDate = new Date().getTime();
        var cmd = this.currentSocket == this.hallSocket ? CMDConfig.SEND_HEARTBEAT1 : CMDConfig.SEND_HEARTBEAT2;
        if (this.currentSocket.connected) 
        {
            this.currentSocket.send(cmd, {});
            this.sendHeartbeatTimers = egret.setTimeout(this.sendHeartbeat, this, 30 * 1000);
        }
    }

    /**
     *收到心跳包 
    */
    public onHeartbeat1(): void 
    {
    }

    /**
     *收到心跳包 
    */
    public onHeartbeat2(): void 
    {
    }

    //设置是否是相同帐号登录
    public setIsThrowOut(falg: Boolean): void 
    {
        this.isThrowOut = falg;
    }

    //游戏进入后台
    public gameHide(): void 
    {
        AppData.getInstance().isGameHide = true;
    }

    //游戏恢复到前台
    public gameShow(): void 
    {
        AppData.getInstance().isGameHide = false;
    }
    
    //当网络断开
    public onSocketClose(data: any): void 
    {
        console.log(">>>onSocketClose");
    }
}

window["ReConnectedModule"] || (window["ReConnectedModule"] = ReConnectedModule);
